package com.kuangstudy.service.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;


/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/20 18:42
 */
@Service
@Slf4j
public class RedisCreatorIdService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis自增id，实现分布式id
     * @return
     */
    public Long incrmentid(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        // 计数器累加 
        Long increment = entityIdCounter.incrementAndGet();
        // 或者
        //Long increment = redisTemplate.opsForValue().increment(key);
        return increment;
    }

}